/*
 *  Copyright 2013 Utkin Dmitry
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#include <QDebug>
#include <QCoreApplication>
#include <google/protobuf/stubs/common.h>
#include <protoqtrpc/RpcController.h>
#include <protoqtrpc/location/LocationRpcChannel.h>
#include "protoqtrpc/samples/EchoServiceMultiresponse.pb.h"

// example of client that uses LocationService to find a service

class MultiresponseClient: public ::google::protobuf::Closure
{
public:
    MultiresponseClient():
        mClient(&mChannel),
        mResponseCount(0)
    {

    }

    virtual ~MultiresponseClient()
    {

    }

    bool connect()
    {
        if (!mChannel.connectToService(mClient.descriptor()))
        {
            qWarning() << "Error: Can't connect to service";
            return false;
        }

        return true;
    }

    bool start()
    {
        mRequest.set_request("Hello, World!");

        // invoke remote method
        mClient.echo(&mController, &mRequest, &mResponse, this);

        if (mController.Failed())
        {
            qDebug() << "Error: " << mController.ErrorText().c_str();
            return false;
        }
        return true;
    }

protected:
    virtual void Run()
    {
        if (mController.IsCanceled())
        {
            QCoreApplication::instance()->quit();
            return;
        }

        qDebug() << "Result: \"" << mResponse.response().c_str() << "\"";
        ++mResponseCount;
        // cancel multiresponse request after 5 responses
        if (mResponseCount > 5)
        {
            mController.StartCancel();
        }
    }

private:
    protoqtrpc::RpcController mController;
    protoqtrpc::location::LocationRpcChannel mChannel;
    protoqtrpc::samples::EchoServiceMultiresponse::Stub mClient;
    protoqtrpc::samples::EchoRequest mRequest;
    protoqtrpc::samples::EchoResponse mResponse;
    int mResponseCount;
};


int main(int argc, char** argv)
{
    QCoreApplication app(argc, argv);

    MultiresponseClient client;

    if (!client.connect())
        return 1;

    if (!client.start())
        return 2;

    return app.exec();
}
